<?php
/**
 * 日志管理 - JBlog
 * 
 * @copyright (c) 2008-2010 JBlog (www.lisijie.org)
 * @author lisijie <lisijie86@gmail.com>
 * @version $Id: mod_blog.php 546 2010-07-21 09:48:31Z lisijie86 $
*/

!defined('IN_ADMIN') && exit('Access Denied!');

check_perm_prompt('blog');

require_once JBLOG_INC.'func_post.php';

empty($ac) && $ac = 'list';

//列表
if ( $ac == 'list' ) {
	
	initGP(array('page','cateid','userid','keyword','status','order','ascdesc'));
	
	$page = max(1, intval($page));
	$pagesize = 20;
	$offset = ($page-1)*$pagesize;
	$url = "?mod=blog&order={$order}&ascdesc={$ascdesc}&cateid={$cateid}&userid={$userid}&status={$status}&keyword=".rawurlencode($keyword);
	$wheresql = "p.`type` = 'blog'";
	if ( in_array($order, array('id','views','comments')) && in_array($ascdesc, array('asc','desc')) ) {
		$ordersql = "p.{$order} {$ascdesc}";
	} else {
		$ordersql = "p.id DESC";
	}
	//非管理员只能看到自己的日志
	if ( !is_admin() ) {
		$wheresql .= " AND p.userid = '$_USER[id]'";
	}
	if ( $cateid ) $wheresql .= " AND p.cateid = '{$cateid}'";
	if ( $userid ) $wheresql .= " AND p.userid = '{$userid}'";
	if ( $keyword ) $wheresql .= " AND p.title LIKE '%{$keyword}%'";
	if ( $status !== '' ) $wheresql .= " AND p.`status` = '{$status}'";
	$count = $db->count('post AS p', $wheresql);
	if ( $count ) {
		$sql = "SELECT p.id,p.cateid,p.title,p.userid,p.username,p.views,p.comments,p.dateline,p.status,p.password,c.catename FROM ".tname('post')." p LEFT JOIN ".tname('cate')." c ON p.cateid = c.id 
		WHERE $wheresql ORDER BY $ordersql LIMIT $offset, $pagesize";
		$result = $db->fetch_all($sql);
	}
	include admin_tpl('blog');
	
//撰写
} elseif ( $ac == 'write' ) {
	
	initGP('id','GP','int');
	
	get_cache('blogmeta');
	
	if ( !$id ) {
		check_perm_prompt('blog','post'); //发表权限
	} else {
		check_perm_prompt('blog','edit'); //编辑权限
	}
	
	if ( check_submit() ) {
		
		if ( empty($_POST['title']) || empty($_POST['cateid']) ) {
			prompt(__('文章标题和分类不能为空。'));
		}
		$old = array();
		if ( $id ) {
			$old = get_post($id);
		}
		
		$cate = $db->fetch_one_array("SELECT id,`type`,children FROM ".tname('cate')." WHERE id = '".intval($_POST['cateid'])."'");
		if ( !$cate || $cate['type'] != 'blog' ) {
			prompt(__('分类不存在。'));
		}
		if ( $cate['children'] > 0 ) {
			prompt(__('该分类下还有子分类，请先删除或移动子分类再删除父分类。'));
		}
		
		initGP(array('year','month','day','hour','minute','second'),'P','int');
		$posttime = mktime($hour, $minute, $second, $month, $day, $year);
		if ( !$posttime ) $posttime = NOW;
		$_POST['dateline'] = $posttime;
		
		$id = post_post($_POST, $old); //发布内容
		
		//添加日历
		$yearmonth = get_date($posttime, 'Ym');
		$day = get_date($posttime, 'j');
		if ( $old ) {
			$db->update('calendar', array('yearmonth'=>$yearmonth, 'day'=>$day), array('postid'=>$id));
		} else {
			$db->insert('calendar', array('yearmonth'=>$yearmonth,'day'=>$day,'postid'=>$id));
		}
		
		//检查文章附件
		$attachments = get_cookie('upload_attachments');

		if ( !empty($attachments) && preg_match('/^[0-9]+(,[0-9]+)+?$/', $attachments) ) {
			$db->query("UPDATE ".tname('attach')." SET postid = '$id' WHERE id IN ($attachments)");
			set_cookie('upload_attachments');
		}
		
		do_action('blog_submit', $_POST, $old);

		redirect('?mod=blog&ac=list');
		
	} else {
		
		$blog = array('commentstatus'=>1);
		//热门标签
		$hottags = '';
		$query = $db->query("SELECT * FROM ".tname('tag')." ORDER BY `count` LIMIT 50");
		while ( $row = $db->fetch_array($query) ) {
			$hottags .= '<a href="javascript:;">'.$row['tagname'].'</a>';
		}
		//编辑
		if ( $id ) {
			$blog = get_post($id);
			if ( !is_admin() && $blog['userid'] != $_USER['id'] ) {
				prompt(__('对不起，你没有权限执行这项操作。'));
			} 
			foreach ($blog as $key => $val) {
				$blog[$key] = my_htmlspecialchars($val);
			}
		}
		$datetime = getdate($blog['dateline']?$blog['dateline']:NOW);
		
		do_action('blog_write');

	}
	
	include admin_tpl('blogwrite');
	
//删除文章
} elseif ( $ac == 'delete' ) {
	
	check_perm_prompt('blog','del');
	
	$ids = $_POST['id'];
	if ( empty($ids) ) $ids = array(intval($_GET['id']));
	//删除单篇
	if ( !is_array($ids) ) {
		$userid = $db->result("SELECT userid FROM ".tname('post')." WHERE id = '$ids'");
		if ( !is_admin() && $userid != $_USER['id'] ) {
			prompt(__('对不起，你没有权限执行这项操作。'));
		}
	//批量删除
	} else {
		$temp = array();
		$query = $db->query("SELECT id,userid FROM ".tname('post')." WHERE id IN (".simplode($ids).")");
		while ( $row = $db->fetch_array($query) ) {
			if ( !is_admin() && $row['userid'] != $_USER['id'] ) {
				continue;
			}
			$temp[] = $row['id'];
		}
		$ids = $temp;
	}
	
	del_post($ids);
	
	do_action('blog_delete', $ids);
	
	redirect($_USER['refer']);
	
//修改状态
} elseif ( $ac == 'upstat') {
	
	check_perm_prompt('blog','check');
	
	$ids = $_POST['id'];
	$status = intval($_POST['status']);
	foreach ( (array)$ids as $key => $val ) {
		if ( !$val || !is_numeric($val) ) unset($ids[$key]);
	}
	if ( $ids ) {
		$db->update('post', array('status'=>$status), array('id'=>$ids));
	}
	
	do_action('blog_upstat', $ids);
	
	redirect($_USER['refer']);
	
//移动
} elseif ( $ac == 'move' ) {
	
	check_perm_prompt('blog','check');
	
	$ids = $_POST['id'];
	$cateid = intval($_POST['cateid']);
	$cate = $db->fetch_one_array("SELECT id,`type`,children FROM ".tname('cate')." WHERE id = '$cateid'");
	if ( $cate['type'] == 'blog' && ! $cate['children'] ) {
		foreach ( (array)$ids as $key => $val ) {
			if ( !$val || !is_numeric($val) ) unset($ids[$key]);
		}
		if ( $ids ) {
			$db->update('post', array('cateid'=>$cateid), array('id'=>$ids));
		}
		
		do_action('blog_move', $ids, $cateid);
	}
	
	redirect($_USER['refer']);	
	
//分类管理
} elseif ( $ac == 'category' ) {
	
	if ( !is_admin() ) {
		prompt(__('对不起，你没有权限执行这项操作。'));
	}
	
	empty($do) && $do = 'list';
	
	//分类列表	
	if ( $do == 'list' ) {
		
		initGP(array('page'));
		
		$page = max(1, intval($page));
		$pagesize = 20;
		$offset = ($page-1)*$pagesize;
		$url = "?mod=blog&ac=category";
		$wheresql = "`type` = 'blog'";
		$count = $db->count('cate', $wheresql);
		$result = array();
		if ( $count ) {
			$parents = $children = array();
			$sql = "SELECT * FROM ".tname('cate')." WHERE `type` = 'blog' ORDER BY orderid LIMIT $offset, $pagesize";
			$query = $db->query($sql);
			while ( $row = $db->fetch_array($query) ) {
				if ( $row['parentid'] > 0 ) {
					$row['catename'] = '&nbsp;&nbsp;├ '.$row['catename'];
					$children[$row['parentid']][] = $row;
				} else {
					$parents[] = $row;
				}
			}
			foreach ( $parents as $row ) {
				$result[] = $row;
				if ( isset($children[$row['id']]) ) {
					foreach ( $children[$row['id']] as $child ) {
						$result[] = $child;
					}
				}
			}
		}
		
		do_action('blog_category_list');
		
	} elseif ( $do == 'add' ) {
		
		check_perm_prompt('blog','addcate');
		
		do_action('blog_category_add');
		
	//编辑分类
	} elseif ( $do == 'edit' ) {
		
		check_perm_prompt('blog','editcate');
		
		initGP('id','G','int');
		$cate = $db->fetch_one_array("SELECT * FROM ".tname('cate')." WHERE id = '$id'");
		if ( $cate ) {
			$query = $db->query("SELECT * FROM ".tname('meta')." WHERE `table` = 'cate' AND dataid = '$id'");
			while ($row = $db->fetch_array($query)) {
				$cate[$row['var']] = $row['value'];
			}
		}
		
		do_action('blog_category_edit');
		
	//更新排序
	} elseif ( $do == 'update' ) {
		
		$order = $_POST['order'];
		$upcate = array();
		if ( $order ) {
			foreach ( $order as $_cid => $_orderid ) {
				$upcate[$_cid]['orderid'] = intval($_orderid);
				$upcate[$_cid]['count'] = $db->count('post', "`type` = 'blog' AND cateid = '$_cid'");
			}
			foreach ( $upcate as $_cid => $updata ) {
				$db->update('cate', $updata, array('id'=>$_cid));
			}
		}
		recache('cate'); //刷新缓存
		
		do_action('blog_category_update');
		
		redirect('?mod=blog&ac=category');
		
	//保存分类
	} elseif ( $do == 'save' ) {
		
		initGP(array('id', 'parentid', 'catename', 'alias', 'orderid', 'keywords', 'description','redirect'), 'P');
		
		if ( empty($catename) ) prompt(__('分类名称不能为空。'));
		$keywords = check_str($keywords);
		$description = check_str($description);
		if ( !preg_match('/^[a-z]+[a-z0-9\-_\.]+$/i',$alias) ) {
			$alias = '';
		}
		
		$data = array(
			'type' => 'blog',
			'parentid' => intval($parentid),
			'catename' => check_str($catename),
			'orderid' => intval($orderid)
		);
		
		if ( $data['parentid'] ) {
			if ( $data['parentid'] == $id ) {
				prompt(__('父分类无效。'));
			}		
			$parent = $db->fetch_one_array("SELECT id,`count`,children,`type` FROM ".tname('cate')." WHERE id = '$data[parentid]'");
			if ( $parent['type'] != 'blog' ) {
				$data['parentid'] = 0;
			} elseif ( $parent['count'] > 0 ) {
				prompt(__('父级分类的文章数必须为0。'));
			}
		}
		
		if ( $id && is_numeric($id) ) {
			
			check_perm_prompt('blog','editcate');
			
			$db->update('cate', $data, array('id' => $id));
			$meta = array(
				array('var'=>'alias', 'value'=>$alias),
				array('var'=>'keywords', 'value'=>$keywords),
				array('var'=>'description', 'value'=>$description),
				array('var'=>'redirect', 'value'=>$redirect)
			);
			foreach ($meta as $m ) {
				if ( !$db->result("SELECT id FROM ".tname('meta')." WHERE `table` = 'cate' AND `dataid` = '$id' AND `var` = '$m[var]'") ) {
					$m['table'] = 'cate';
					$m['dataid'] = $id;
					$db->insert('meta', $m);
				} else {
					$db->update('meta', array('value'=>$m['value']), array('table'=>'cate', 'dataid'=>$id, 'var'=>$m['var']));
				}
			}
			
			recount_cate_children();
			
			recache('cate'); //刷新缓存
			
			do_action('blog_category_save');
			
			redirect('?mod=blog&ac=category');
			
		} else {
			
			check_perm_prompt('blog','addcate');
			
			$id = $db->insert('cate', $data);
			$meta = array(
				array('table'=>'cate', 'dataid'=>$id, 'var'=>'alias', 'value'=>$alias),
				array('table'=>'cate', 'dataid'=>$id, 'var'=>'keywords', 'value'=>$keywords),
				array('table'=>'cate', 'dataid'=>$id, 'var'=>'description', 'value'=>$description),
				array('table'=>'cate', 'dataid'=>$id, 'var'=>'redirect', 'value'=>$redirect)
			);
			foreach ($meta as $m) $db->insert('meta', $m);
			
			recount_cate_children();
			
			recache('cate'); //刷新缓存
			
			do_action('blog_category_save');
			
			redirect('?mod=blog&ac=category');
			
		}
	//删除分类
	} elseif ( $do == 'del' ) {
		
		check_perm_prompt('blog','delcate');
		
		if ( $id = intval($_GET['id']) ) {
			
			if ( $id != 1 ) {
				
				$cate = $db->fetch_one_array("SELECT id,parentid,children,`type` FROM ".tname('cate')." WHERE id = '$id'");
				if ( $cate['type'] == 'blog' ) {
					
					if ( $cate['parentid']==0 && $cate['children'] > 0 ) {
						prompt(__('该分类下还有子分类，请先删除或移动子分类再删除父分类。'));
					}
					$db->delete('cate', array('id'=>$id)); //删除主表记录
					$db->delete('meta', array('table'=>'cate','dataid'=>$id)); //删除附加字段
					$db->update('post', array('cateid'=>1), array('cateid'=>$id)); //将分类下的文章分类设为1（默认分类）
					recount_cate_children();

					recache('cate'); //刷新缓存
					
					do_action('blog_category_del');
					
				}
			}
		}
		
		redirect('?mod=blog&ac=category');
		
	//合并分类
	} elseif ( $do == 'merge' ) {
		check_perm_prompt('blog','delcate'); //合并必须具备删除权限
		$idarr = getGP('id','P','array');
		$tocid = getGP('tocid','P','int');
		$idarr = array_unique($idarr);
		$idstr = implode(',', $idarr);
		if ( !preg_match('/^[0-9,]+$/', $idstr) ) prompt(__('非法ID参数。'));
		if ( $db->result("SELECT id FROM ".tname('cate')." WHERE id = '$tocid'") ) {
			$db->query("UPDATE ".tname('post')." SET cateid = '$tocid' WHERE cateid IN ($idstr) AND cateid <> '$tocid' ");
			$db->query("DELETE FROM ".tname('cate')." WHERE id IN ($idstr) AND id <> '$tocid' ");
			recache('cate');
			$count = $db->count('post', "cateid='$tocid'");
			$db->update('cate', array('count'=>$count), array('id'=>$tocid));
			do_action('blog_category_merge');
		}
		redirect('?mod=blog&ac=category');		
	}
	include admin_tpl('blogcate');

//--------自定义域------
} elseif ( $ac == 'blogmeta' ) {
	
	if ( !is_founder() ) {
		prompt(__('对不起，你没有权限执行这项操作。'));
	}
	
	empty($do) && $do = 'list';
	
	//保存
	if ( $do == 'save' ) {
		
		$name = trim($_POST['name']);
		if ( !preg_match("/^[\x{4e00}-\x{9fa5}A-Za-z0-9_]+$/u", $name) ) {
			prompt(__('自定义域名称必须由汉字、字母、数字、下划线构成。'));
		}
		$query = $db->query("DESC ".tname('post')."");
		while ( $row = $db->fetch_array($query) ) {
			$fields[] = $row['Field'];
		}
		if ( in_array($name, $fields) ) {
			prompt(__('名称与系统字段冲突，请重新填写。'));
		}
		if ( $db->result("SELECT `name` FROM ".tname('config')." WHERE `name` = '$name' AND `type` != 'blogmeta'") ) {
			prompt(__('该配置项已存在，请换一个名称。'));
		}
		$value = (array)$_POST['value'];
		$data = array(
			'name' => $name,
			'value' => my_serialize($value),
			'type' => 'blogmeta'
		);
		$db->insert('config', $data, true);
		recache('blogmeta');
		redirect('admin.php?mod=blog&ac=blogmeta');
		
	//编辑
	} elseif ( $do == 'edit' ) {
		
		$name = trim($_GET['name']);
		$meta = $db->fetch_one_array("SELECT * FROM ".tname('config')." WHERE `name` = '$name' AND `type` = 'blogmeta'");
		if ( $meta ) {
			$meta['value'] = unserialize($meta['value']);
			$meta['value']['name'] = $meta['name'];
			$meta = $meta['value'];
		}
		
	//删除
	} elseif ( $do == 'del' ) {
		
		$name = trim($_GET['name']);
		$db->delete('config', array('name'=>$name, 'type'=>'blogmeta'));
		recache('blogmeta');
		redirect('admin.php?mod=blog&ac=blogmeta');
		
	} elseif ( $do == 'list' ) {
	
		$result = array();
		$query = $db->query("SELECT `name`,`value` FROM ".tname('config')." WHERE `type` = 'blogmeta'");
		while ( $row = $db->fetch_array($query) ) {
			$row['value'] = unserialize($row['value']);
			$row['value']['name'] = $row['name'];
			$result[] = $row['value'];
		}
	
	}
	
	include admin_tpl('blogmeta');
	
}

//重新统计子分类数目
function recount_cate_children() {
	global $db;
	$query = $db->query("SELECT * FROM ".tname('cate')." WHERE `type` = 'blog'");
	$old = $new = array();
	while ( $row = $db->fetch_array($query) ) {
		if ( $row['parentid'] == 0 ) {
			$old[$row['id']] = $row['children'];
		} else {
			$new[$row['parentid']] ++;
		}
	}
	foreach ( $old as $id => $num ) {
		if ( $new[$id] != $num ) {
			$db->update('cate',array('children'=>intval($new[$id])), array('id'=>$id));
		}
	}
}

//文章自动保存
function auto_save($post) {
	if ( empty($post['title']) ) {
		$post['title'] = __('未命名文章');
	}
	if ( empty($post['cid']) ) {
		$post['cateid'] = 1;
	}
	$post['status'] = -1;
	return post_post($post);
}
?>